package com.commutersconnect.snippet

import scala.xml.{NodeSeq, Text}
import net.liftweb._
import mapper.By
import http.{S, SHtml}
import http.js.JsCmds.{SetHtml, Noop, FocusOnLoad, Alert}
import http.js.JE._
import util._
import common._
import java.util.Date
import com.commutersconnect.lib._
import Helpers._

import com.commutersconnect.model.{User, Report}

object Registration {
  def render = {
    println("Looks like we are in the render method.")

    //We will always be collecting a username from you.
    var email = ""

    //If you are a current user, we get current password.
    var password = ""

    //And if you are a new user, we get a newPassword as well as some
    //additional fields.
    var newPassword = ""
    var firstName = ""
    var lastName = ""
    var organization = ""
    var mobilePhone = ""

    //Now, we first check to see if the user is currently already logged in,
    //if so then we are going to remove the registration form entirely and
    //leave the toolbars.  We will leave the link that lets you logout if we
    //have the wrong user.
    SHtml.idMemoize( indexPage => {
      User.currentUser.map( curUser => {
        "#registrationForm" #> NodeSeq.Empty &
        "#welcomeBack" #> (
            ".userFirstName *" #> curUser.firstName.is &
            ".wrongUser [onclick]" #> SHtml.ajaxInvoke(() => {
                User.logout
                indexPage.setHtml //TODO Find out why this is doing a page reload..
              })
        ) &
        ".report" #> curUser.reports.map( report=>
          ".reportSubject *" #> report.subject &
          ".reportSubject [href]" #> ViewReportSnippet.viewReportUrl(report) )
      }) openOr
        //If you are not logged in, we strip out the reports, toolbars, and
        //welcome back message from the index.
        ("#reports" #> "" &
        "#toolbars" #> "" &
        "#welcomeBack" #> "" &
        "@emailAddress" #> FocusOnLoad(SHtml.text(email, email = _)) &
        "@password" #> SHtml.password(password, password = _) &
        "#signInButton" #> SHtml.ajaxSubmit("Sign In", () => {
          User.find(By(User.email, email)).map(user => {
              if (user.password match_? password) {
                User.logUserIn(user)
                S.clearCurrentNotices//We don't want any lingering errors from previous attempts.
                indexPage.setHtml    //And we rerun the full template on login.
              } else {
                S.error("Could not validate username/password.")
                Noop
              }
            }) openOr {
            S.error("Could not validate username/password.")
            Noop
          }
          }) &
        "@firstName" #> SHtml.text(firstName, firstName = _) &
        "@lastName" #> SHtml.text(lastName, lastName = _) &
        "@organization" #> SHtml.text(organization, organization = _) &
        "@mobilePhone" #> SHtml.text(mobilePhone, mobilePhone = _) &
        "@newPassword" #> SHtml.password(newPassword, newPassword = _) &
        "#signUpButton" #> SHtml.ajaxSubmit("Sign In", () => {
            println("We are processing a new user.")
            val newUser = User.create
              .email(email)
              .password(newPassword)
              .firstName(firstName)
              .lastName(lastName)
              .organization(organization)
              .phone(mobilePhone)
            newUser.validate match {
              case Nil => {
                newUser.save
                User.logUserIn(newUser)
                S.notice("Welcome to Commuters Connect")
                indexPage.setHtml
              }
              case errors => {
                S.error(errors)
                Noop
              }
            }
        })
      )
    })
  }
}

